package ua.keeper.query;

import java.util.ArrayList;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DocHList
{
    private SQLiteDatabase db_;
    private int clientId_ = 0;
    /*****************************************************************************************/
    
    public ArrayList<DocHListItem> list = new ArrayList<DocHListItem>();
    /*****************************************************************************************/
    
    DocHList(SQLiteDatabase dataBase, int clientId)
    {
    	clientId_ = clientId;
    	Log.i("DocHList", "Constructor");
    	Log.i("DocHList", "Client ID = " + Integer.toString(clientId));
    	db_ = dataBase;
    	if (!db_.isOpen())
    	{
    		Log.w("DocHList.Init()", "DataBase is not opened!");
    		return;
    	}
    	fillList();
    }
    
    /*****************************************************************************************/
    private void fillList()
    {
    	Cursor cursor = db_.rawQuery("SELECT query_h.id_, COUNT(query_d.id_), SUM(query_d.q * goods.price)" +
    									" FROM query_h" +
    									" LEFT OUTER JOIN query_d ON query_d.head = query_h.id_" +
    									" LEFT OUTER JOIN goods ON query_d.goods = goods.id_" +
    									" WHERE client = ? GROUP BY query_h.id_",
    									new String[] { Integer.toString(clientId_) });
    	int queryCount = cursor.getCount();
    	Log.i("DocHList", "Query count = " + Integer.toString(queryCount));
    	if (queryCount == 0)
    	{
    		Log.w("DocHList.getList()", "Cursor is empty!");
    	}
    	
    	cursor.moveToFirst();
    	while(!cursor.isAfterLast())
        {
    		DocHListItem item = new DocHListItem(cursor.getInt(0),
    											 	"Заявка " + (cursor.getPosition() + 1),
    											 	cursor.getDouble(2),
    											 	cursor.getInt(1)
    											 );
    		list.add(item);
    		cursor.moveToNext();
        }
        cursor.close();
        
        // Add "add" line
        list.add(new DocHListItem(-1, "", 0, 0));
    }
    /*****************************************************************************************/
}

